export default class Lazyimg {
    constructor(el, src, options, imgRender) {
        this.el = el
        this.src = src
        this.options = options
        this.imgRender = imgRender

        this.loaded = false
        this.state = {
            loading: false,
            error: false,
        }
    }



    checkIsVisible() {
        let distTop = this.el.getBoundingClientRect().top
        console.log(distTop, window.innerHeight * this.options.preload)
        return distTop <= window.innerHeight * this.options.preload
    }

    loadImg() {
        this.imgRender(this, 'loading')

        imgLoad(this.src).then(() => {
            this.state.loading = true
            this.imgRender(this, 'ok')
            this.loaded = true
        }, () => {
            this.state.loading = true
            this.imgRender(this, 'error')
            this.loaded = true
        })
    }

}

function imgLoad (src) {
    return new Promise((resolve, reject) => {
        const oImg = new Image()
        oImg.src = src
        oImg.onload = resolve
        oImg.onerror = reject
    })
}